import {CircularProgress, Collapse} from "@mui/material";
import DGListViewItem from "./DGListViewItem.tsx";
import {ExpandMore} from "@mui/icons-material";

import Brightness7SharpIcon from "@mui/icons-material/Brightness7Sharp";
import Brightness4SharpIcon from "@mui/icons-material/Brightness4Sharp";
import LightbulbSharpIcon from "@mui/icons-material/LightbulbSharp";
import CheckSharpIcon from "@mui/icons-material/CheckSharp";
import AppProvider from "../sources/AppProvider.ts";
import {FC, useEffect, useState} from "react";
import DGToast from "./DGToast.tsx";
import {AlertColor} from "@mui/material/Alert/Alert";
import DGConnect from "../sources/DGConnect.ts";
import DGListView from "./DGListView.tsx";

interface DGToastProps {
    state: boolean,
    severity: AlertColor,
    text: string
}

interface DGChangeThemeProps {
    state?: boolean,
    time?: number,
    NoBackground?: boolean;
}

const DGChangeTheme: FC<DGChangeThemeProps> = ({state, time, NoBackground}) => {
    // 主题模式上下文
    const TC = AppProvider.useAppThemeContext();
    // 全局上下文
    const App = AppProvider.useAppContext();
    // Toast 弹窗
    const [toast, setToast] = useState<DGToastProps>({state: false, severity: "info", text: ""});
    // 列表展开
    const [Open, setOpen] = useState(false);
    // 显示当前模式文字
    const [MyThemeText, setMyThemeText] = useState("");
    // 加载状态
    const [loading, setLoading] = useState<number | null>(null);
    // 延时存储
    const [Time1, setTime1] = useState(Number);
    const [Time2, setTime2] = useState(Number);

    // 切换模式函数 handleSM = handleSwitchMode
    const handleSM = (mode: number) => {
        // 取消定时
        clearTimeout(Time1);
        clearTimeout(Time2);
        // 验证，取消错误
        if (App && TC) {
            // 重复选中，加感叹号为未登录时的判断
            if ((!App.info && TC.mode === mode) || (App.info && App.info["theme"] === mode)) return setOpen(false);
            // 开始加载
            setLoading(mode);
            // 未登录时更改主题模式
            if (!App.info) {
                setTime1(setTimeout(() => {
                    // 更新主题模式
                    TC.setThemeMode(false, mode);
                    // 清除加载
                    setLoading(null);
                    // 延时执行关闭折叠
                    setTime2(setTimeout(() => setOpen(false), 500));
                }, 1000));
            } else {
                // 已登陆时更改主题模式
                setTime1(setTimeout(() => {
                    // 发起更改模式请求
                    DGConnect.POST(JSON.stringify({
                        info: "changeTheme", theme: mode
                    }), result => {
                        // 返回错误信息
                        if (result['data']['code'] !== 200) return setToast({
                            state: true, severity: "error", text: result['data']['message']
                        });
                        // 更新用户信息
                        App.setUserInfo(result['data']['result']);
                        // 刷新主题模式
                        TC.setThemeMode(true, result['data']['result']['theme']);
                        // 清除加载
                        setLoading(null);
                        // 延时执行关闭折叠
                        setTime2(setTimeout(() => setOpen(false), 500));
                    }, error => {
                        // 清除加载
                        setLoading(null);
                        // 提示更改失败
                        setToast({
                            state: true,
                            severity: "error",
                            text: "遇到了一些问题，请尝试重试，或者及时联系我们！错误信息：" + error['stack']
                        });
                    });
                }, 1000));
            }
        }
    }

    useEffect(() => {
        // 已登陆时执行
        if (App!.info && App!.info["theme"] === 0) setMyThemeText("跟随系统");
        if (App!.info && App!.info["theme"] === 1) setMyThemeText("浅色模式");
        if (App!.info && App!.info["theme"] === 2) setMyThemeText("深色模式");
        // 未登录时执行
        if (!App!.info && TC!.mode === 0) setMyThemeText("跟随系统");
        if (!App!.info && TC!.mode === 1) setMyThemeText("浅色模式");
        if (!App!.info && TC!.mode === 2) setMyThemeText("深色模式");
    }, [App, App?.info, TC, TC?.mode]);


    return (<>
            {/* Toast 组件 */}
            <DGToast state={toast} close={() => setToast({state: false, severity: toast.severity, text: toast.text})}/>
            {/* 列表 */}
            <DGListView animation={state} time={time} NoBackground={NoBackground}>
                {/* 主题更改列表选项 */}
                <DGListViewItem
                    icon={<LightbulbSharpIcon/>}
                    title={"模式：" + MyThemeText} subText="登陆后会同步账号内容"
                    rIcon={<ExpandMore style={{
                        transition: "all 0.3s ease", transform: Open ? "rotate(180deg)" : "rotate(0deg)"
                    }}/>}
                    onClick={() => setOpen(!Open)} disabled={loading !== null}/>
                {/* 展开组件 */}
                <Collapse in={Open} timeout="auto" unmountOnExit>
                    {/* 跟随系统列表选项 */}
                    <DGListViewItem
                        title="跟随系统" style={{paddingLeft: "35px"}}
                        onClick={() => handleSM(0)} disabled={loading !== null}
                        icon={<>
                            {/* 勾选图标 */}
                            {App!.info && App!.info["theme"] === 0 && <CheckSharpIcon/>}
                            {!App!.info && TC!.mode === 0 && <CheckSharpIcon/>}
                            {/* 默认图标 */}
                            {App!.info && App!.info["theme"] !== 0 && loading !== 0 && <LightbulbSharpIcon/>}
                            {!App!.info && TC!.mode !== 0 && loading !== 0 &&
                                <LightbulbSharpIcon/>}
                            {/* 加载图标 */}
                            {App!.info && App!.info["theme"] !== 0 && loading === 0 && <CircularProgress size={24}/>}
                            {!App!.info && TC!.mode !== 0 && loading === 0 && <CircularProgress size={24}/>}
                        </>}/>
                    {/* 浅色模式列表选项 */}
                    <DGListViewItem
                        title="浅色模式" style={{paddingLeft: "35px"}}
                        onClick={() => handleSM(1)} disabled={loading !== null}
                        icon={<>
                            {/* 勾选图标 */}
                            {App!.info && App!.info["theme"] === 1 && <CheckSharpIcon/>}
                            {!App!.info && TC!.mode === 1 && <CheckSharpIcon/>}
                            {/* 默认图标 */}
                            {App!.info && App!.info["theme"] !== 1 && loading !== 1 && <Brightness7SharpIcon/>}
                            {!App!.info && TC!.mode !== 1 && loading !== 1 && <Brightness7SharpIcon/>}
                            {/* 加载图标 */}
                            {App!.info && App!.info["theme"] !== 1 && loading === 1 && <CircularProgress size={24}/>}
                            {!App!.info && TC!.mode !== 1 && loading === 1 && <CircularProgress size={24}/>}
                        </>}
                    />
                    {/* 深色模式列表选项 */}
                    <DGListViewItem
                        title="深色模式" style={{paddingLeft: "35px"}}
                        onClick={() => handleSM(2)} disabled={loading !== null}
                        icon={<>
                            {/* 勾选图标 */}
                            {App!.info && App!.info["theme"] === 2 && <CheckSharpIcon/>}
                            {!App!.info && TC!.mode === 2 && <CheckSharpIcon/>}
                            {/* 默认图标 */}
                            {App!.info && App!.info["theme"] !== 2 && loading !== 2 && <Brightness4SharpIcon/>}
                            {!App!.info && TC!.mode !== 2 && loading !== 2 && <Brightness4SharpIcon/>}
                            {/* 加载图标 */}
                            {App!.info && App!.info["theme"] !== 2 && loading === 2 && <CircularProgress size={24}/>}
                            {!App!.info && TC!.mode !== 2 && loading === 2 && <CircularProgress size={24}/>}
                        </>}/>
                </Collapse>
            </DGListView>
        </>
    );
}
export default DGChangeTheme;